package org.bling.star.server.coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.bling.star.common.command.BaseCommand;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

public class CommandEncoder extends MessageToByteEncoder<BaseCommand> {

    @Override
    protected void encode(ChannelHandlerContext ctx, BaseCommand msg, ByteBuf out) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(msg);
        oos.flush();

        byte[] data = baos.toByteArray();
        out.writeInt(data.length);
        out.writeBytes(data);
    }
}